<?php
/*
 * Copyright 2009 Eat Local Food, LLC
 * Copyright (c) 2008 osCommerce (this file was written after
 * code review of osCommerce).
 *
 * This file is part of gwtCommerce.
 *
 * gwtCommerce is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * gwtCommerce is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with gwtCommerce.  If not, see <http://www.gnu.org/licenses/>.
 */

require_once('includes/functions/module_functions.php');
class plugnpay_ss {

	// class constructor
	function plugnpay_ss()
	{
		$this->module_key = 'MODULE_PAYMENT_PLUGNPAYSS';
		$this->code = 'plugnpay_ss';
		$this->enabled = ((MODULE_PAYMENT_PLUGNPAYSS_STATUS == 'true') ? true : false);
		$this->sort_order = MODULE_PAYMENT_PLUGNPAYSS_SORT_ORDER;
		$this->status_id = MODULE_PAYMENT_PLUGNPAYSS_ORDER_STATUS_ID;
		$this->email_footer = false;
	}

	// class methods

	function confirm_zone($params, &$checkout_component)
	{
		return check_zone(MODULE_PAYMENT_PLUGNPAYSS_ZONE, $checkout_component->billTo['country_id'], $checkout_component->billTo['zone_id']);
	}

	function setup(&$params, &$checkout_component)
	{
		$setup['code'] = $this->code;
		$setup['payment_method'] = MODULE_PAYMENT_PLUGNPAYSS_PAYMETHOD;
		$setup['check_cvv'] = ((MODULE_PAYMENT_PLUGNPAYSS_CVV == 'yes') ? true : false);
		$setup['accepted_credit_cards'] = MODULE_PAYMENT_PLUGNPAYSS_ACCEPTED_CC;
		$setup['sort_order'] = $this->sort_order;
		$setup['third_party_payment_process'] = true;
		$setup['pass_cc'] = true;

		$pnp_date = date("YmdHis");
		$pnp_orderId = $pnp_date . $params['accountId'];

		# start building hidden array
		$form_data = array(
                        action_url => 'https://pay1.plugnpay.com/payment/auth.cgi',
			publisher_name => MODULE_PAYMENT_PLUGNPAYSS_LOGIN,
			publisher_email => MODULE_PAYMENT_PLUGNPAYSS_PUBLISHER_EMAIL,
			mode => 'auth',
			convert => 'underscores',
			easycart => '1',
		 	shipinfo => '1',
			client => 'gwtCommerce_SS',
			nostatelist => 'yes',
			card_allowed => MODULE_PAYMENT_PLUGNPAYSS_ACCEPTED_CC,
			orderID => $pnp_orderId,
			authtype => MODULE_PAYMENT_PLUGNPAYSS_CCMODE == 'authonly' ? 'authonly' : 'authpostauth',
			dontsndmail => MODULE_PAYMENT_PLUGNPAYSS_DONTSNDMAIL == 'yes' ? 'yes': 'no',
			order_id => "{$params['accountId']}",
			card_name => 'TOKEN_BILLTONAME',
			card_company => "{$checkout_component->billTo['company']}",
			card_address1 => "{$checkout_component->billTo['street_address']}",
			card_city => "{$checkout_component->billTo['city']}",
			card_state => "{$checkout_component->billTo['state']}",
			card_zip => "{$checkout_component->billTo['postcode']}",
			card_country => "{$checkout_component->billTo['country_iso_code_2']}",
			phone => "{$checkout_component->accountInfo['telephone']}",
			email => "{$checkout_component->accountInfo['email_address']}",
			shipname => 'TOKEN_SHIPTONAME',
			company => "{$checkout_component->shipTo['company']}",	
			address1 => "{$checkout_component->shipTo['street_address']}",
			city => "{$checkout_component->shipTo['city']}",
			state => "{$checkout_component->shipTo['state']}",
			zip => "{$checkout_component->shipTo['postcode']}",
			country => "{$checkout_component->shipTo['country_iso_code_2']}",
			ipaddress => "{$_SERVER['REMOTE_ADDR']}",
			sessionId => "{$params['accountSession']}",
			app_level => MODULE_PAYMENT_PLUGNPAYSS_AVS_LEVEL,
			success_link => HTTPS_SERVER . 'third_party_payment_process.php',
			badcard_link => HTTPS_SERVER . 'third_party_payment_process.php',
			problem_link => HTTPS_SERVER . 'third_party_payment_process.php',
			card_amount => number_format($checkout_component->cart_prices['ot_total']['value'] * $checkout_component->currency['value'], 2),
			currency => "{$checkout_component->currency['code']}",
			currency_value => "{$checkout_component->currency['value']}",
			card_type => 'TOKEN_CREDITCARDTYPE',
			card_number => 'TOKEN_CREDITCARDNUMBER',
			card_exp => 'TOKEN_CREDITCARDEXPIRATIONMONTHSLASHYEAR',
			pass => '1',
			transitiontype => MODULE_PAYMENT_PLUGNPAYSS_TRANSITION_TYPE
		);

		if(MODULE_PAYMENT_PLUGNPAYSS_CVV == 'yes') {
			$form_data['card_cvv'] = 'TOKEN_CREDITCARDCVV';
		}

		$cart = &$checkout_component->cart;
		$sz = sizeof($cart);
		$j = 0;
		for ($i=0; $i< $sz; $i++)
		{
			$j = $i + 1;
			$form_data["item$j"] = $cart[$i]['model'];
			$form_data["cost$j"] = number_format($cart[$i]['cart_price'] * $checkout_component->currency['value'], 2);
			$form_data["quantity$j"] = (string)$cart[$i]['cart_qty'];
			$form_data["description$j"] = $cart[$i]['name'];
		}

		$coupon_value = (double)$checkout_component->cart_prices['ot_coupon']['value'];
		if ($coupon_value != 0) {
			$j++;
			$form_data["item$j"] = $checkout_component->cart_prices['ot_coupon']['title'];
			$form_data["cost$j"] = number_format($coupon_value * $checkout_component->currency['value'], 2);
			$form_data["quantity$j"] = '1';
			$form_data["description$j"] = $checkout_component->cart_prices['ot_coupon']['title'];
		}			

		$form_data["shipping"] = number_format($checkout_component->cart_prices['ot_shipping']['value'] * $checkout_component->currency['value'], 2);
		$form_data["tax"] = number_format($checkout_component->cart_prices['ot_tax']['value'] * $checkout_component->currency['value'], 2);


		if ((MODULE_PAYMENT_PLUGNPAYSS_PAYMETHOD == "onlinecheck") && ($HTTP_POST_VARS['plugnpay_paytype'] == 'echeck')) {
			// use electronic check info - TBD 
			/*
			$form_data['paymethod'] = 'onlinecheck';
			*/
		}
		else {
			// or assume credit card info
			$form_data['paymethod'] = 'credit';
		}

		$setup['third_party_payment_parameters'] = $form_data;

		return $setup;
	}

	function process(&$params, &$checkout_component)
	{
		$FinalStatus = $params['gwt_FinalStatus'];
		$MErrMsg = $params['gwt_MErrMsg'];
		if ($FinalStatus != 'success')
		{
			$checkout_component->errorCode = -1;
			$checkout_component->errorMessage = 'Payment_' . $this->code . '_' . $FinalStatus;
			$checkout_component->paymentErrorMessage = $MErrMsg;

			if ($FinalStatus == null || $FinalStatus == '') {
				$checkout_component->errorMessage = 'Payment_' . $this->code . '_Unknown';
			}
			return;
		}

		$publisher = $params['gwt_publisher_name'];
		if ($publisher != MODULE_PAYMENT_PLUGNPAYSS_LOGIN)
		{
			$checkout_component->errorCode = -1;
			$checkout_component->errorMessage = 'Payment_' . $this->code . '_incorrect_publisher_name';
		}

		$card_amount = number_format($checkout_component->cart_prices['ot_total']['value'] * $checkout_component->currency['value'], 2);
		if ($card_amount != $params['gwt_card_amount'])
		{
			$checkout_component->warningCode = -1;
			$checkout_component->warningMessage = 'card amount calculated ('.$card_amount.') does not match card amount ('.$params['gwt_card_amount'].')submitted';
			return;
		}

		if (MODULE_PAYMENT_PLUGNPAYSS_TRANSITION_TYPE == 'hidden') {
			if (!$this->checkIPAddress())
			{
				$checkout_component->warningCode = -1;
				$checkout_component->warningMessage = 'IP Address is not a PNP IP Address:'.$_SERVER['REMOTE_ADDR'];
				return;	
			}

		}
	}

	function check() {
		if (!isset($this->_check)) {
			$this->_check = check_module($this->module_key);
		}
		return $this->_check;
	}

	function install() {
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Enable PlugnPay Module', 'MODULE_PAYMENT_PLUGNPAYSS_STATUS', 'true', 'Do you want to accept payments through PlugnPay Smart Screens?', '6', '0','true, false', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Login Username', 'MODULE_PAYMENT_PLUGNPAYSS_LOGIN', 'Your Login Name', 'Enter your PlugnPay account username', '6', '0', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Publisher Email', 'MODULE_PAYMENT_PLUGNPAYSS_PUBLISHER_EMAIL', 'Enter Your Email Address', 'The email address you want PlugnPay conformations sent to', '6', '0', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Transaction Mode', 'MODULE_PAYMENT_PLUGNPAYSS_TESTMODE', 'Test', 'Transaction mode used for processing orders', '6', '0', 'Test, Test And Debug, Production', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Require CVV', 'MODULE_PAYMENT_PLUGNPAYSS_CVV', 'yes', 'Ask For CVV information', '6', '0', 'yes, no', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Transaction Method', 'MODULE_PAYMENT_PLUGNPAYSS_PAYMETHOD', 'credit', 'Transaction method used for processing orders.<br><b>NOTE:</b> Selecting \'onlinecheck\' assumes you\'ll offer \'credit\' as well.', '6', '0', 'credit, onlinecheck', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Authorization Type', 'MODULE_PAYMENT_PLUGNPAYSS_CCMODE', 'authpostauth', 'Credit card processing mode', '6', '0', 'authpostauth, authonly', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('Sort Order Of Display', 'MODULE_PAYMENT_PLUGNPAYSS_SORT_ORDER', '1', 'The order in which this payment type is dislayed. Lowest is displayed first.', '6', '0' , now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Customer Notifications', 'MODULE_PAYMENT_PLUGNPAYSS_DONTSNDMAIL', 'yes', 'Should PlugnPay not email a receipt to the customer?', '6', '0', 'yes, no', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_format, configuration_values, date_added) values ('Accepted Credit Cards', 'MODULE_PAYMENT_PLUGNPAYSS_ACCEPTED_CC', 'Mastercard, Visa', 'The credit cards you currently accept', '6', '0', 'multi_select', 'Amex, Discover, Mastercard, Visa', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Set Order Status', 'MODULE_PAYMENT_PLUGNPAYSS_ORDER_STATUS_ID', '0', 'Set the status of orders made with this payment module to this value', '6', '0', 'order_status_list()', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, date_added) values ('AVS Level', 'MODULE_PAYMENT_PLUGNPAYSS_AVS_LEVEL', '0', 'The level of address verification you wish to have. Levels 1-6 0=Off.', '6', '4', now())");
		run_sql("insert into " . TABLE_CONFIGURATION . " (configuration_title, configuration_key, configuration_value, configuration_description, configuration_group_id, sort_order, configuration_values, date_added) values ('Transition Type', 'MODULE_PAYMENT_PLUGNPAYSS_TRANSITION_TYPE', 'get', 'Transition Page Type', '6', '0', 'get, post, hidden', now())");
	}

	function remove() {
		remove_module($this->module_key);
	}
	function checkIPAddress()
	{
		$ipaddress = $_SERVER['REMOTE_ADDR'];
		$pos = strrpos($ipaddress, '.');
		$ipaddress1 = substr($ipaddress, 0, $pos);
		$ipaddress2 = (int)substr($ipaddress, $pos+1);
			
		if ($ipaddress == '96.56.10.14' ||
		    $ipaddress == '69.18.198.4' || 
		    $ipaddress1 == '209.51.176' || 
		    $ipaddress1 == '206.25.10' || 
		    ($ipaddress1 == '209.51.163' && $ipaddress2 > 239) ||
		    ($ipaddress1 == '209.51.171' && $ipaddress2 > 149 && $ipaddress2 < 159)
		   )
		{
			return true;
		}
		return false;
	}
}
?>
